package com.zrrd.gmall.product.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zrrd.gmall.model.product.*;
import com.zrrd.gmall.product.mapper.*;
import com.zrrd.gmall.product.service.SpuInfoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class SpuInfoServiceImpl extends ServiceImpl<SpuInfoMapper, SpuInfo> implements SpuInfoService {

    @Autowired
    private BaseSaleAttrMapper baseSaleAttrMapper;
    @Autowired
    private SpuImageMapper spuImageMapper;
    @Autowired
    private SpuSaleAttrMapper spuSaleAttrMapper;
    @Autowired
    private SpuSaleAttrValueMapper spuSaleAttrValueMapper;


    @Override
    public List<BaseSaleAttr> getBaseSaleAttrList() {
        return baseSaleAttrMapper.selectList(null);
    }

    @Override
    @Transactional
    public void saveSupInfo(SpuInfo spuInfo) {
        //1.保存Spu基本信息->spu_info
        this.save(spuInfo);
        //2.保存Spu图片->spu_image
        List<SpuImage> spuImageList = spuInfo.getSpuImageList();
        for (SpuImage spuImage : spuImageList) {
            spuImage.setSpuId(spuInfo.getId());
            spuImageMapper.insert(spuImage);
        }
        //3.保存Spu销售属性->spu_sale_attr
        List<SpuSaleAttr> spuSaleAttrList = spuInfo.getSpuSaleAttrList();

        if(spuSaleAttrList != null && spuSaleAttrList.size() > 0 ){
            for (SpuSaleAttr spuSaleAttr : spuSaleAttrList) {
                //设置SpuId
                spuSaleAttr.setSpuId(spuInfo.getId());
                //执行保存
                spuSaleAttrMapper.insert(spuSaleAttr);

                //4.保存Spu销售属性值->spu_sale_attr_value
                List<SpuSaleAttrValue> spuSaleAttrValueList = spuSaleAttr.getSpuSaleAttrValueList();

                if(spuSaleAttrValueList != null && spuSaleAttrValueList.size() > 0){
                    //遍历属性值的集合
                    for (SpuSaleAttrValue spuSaleAttrValue : spuSaleAttrValueList) {
                        //设置SpuId
                        spuSaleAttrValue.setSpuId(spuInfo.getId());
                        //设置属性名称
                        spuSaleAttrValue.setSaleAttrName(spuSaleAttr.getSaleAttrName());
                        //执行保存
                        spuSaleAttrValueMapper.insert(spuSaleAttrValue);
                    }
                }
            }
        }
    }


}
